package com.financing.controller.invest;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.shiro.authz.annotation.RequiresRoles;

import com.financing.enums.invest.BidStatus;
import com.financing.model.Data;
import com.financing.model.invest.Bid;
import com.financing.model.invest.Repay;
import com.financing.model.user.User;
import com.financing.service.invest.RepayService;
import com.financing.util.DateUtil;
import com.financing.util.Json;
import com.financing.util.Money;
import com.financing.util.Str;
import com.jfinal.core.Controller;
import com.jfinal.plugin.activerecord.Page;

public class RepayController extends Controller {
	private static RepayService repay = new RepayService();	
	
	
	/**
	 * 我的还款计划
	 */
	@SuppressWarnings("unchecked")
	public void myPlan() { 
		User u = getAttr("user");
		List<Repay> list = repay.findByUser(u.getId(),getPara("month",""));
		double total = 0.0;
		List<Object> res = new ArrayList<Object>();
		Map<String,Integer> mark = new HashMap<String,Integer>();
		for(Repay r : list) {
			r.put("summary", "还款");
			total += r.getPeriodTotal();
			String key = DateUtil.format(r.getRepayTime(), "yyyy年MM月");
			String dayKey = DateUtil.format(r.getRepayTime(), "yyyyMMdd");
			String dayKey2 = DateUtil.format(r.getRepayTime(), "yyyy-MM-dd");
			r.setRepayTime(DateUtil.parse(dayKey2+" 23:59:59"));
			if(mark.containsKey(key)) {
				Map<String,Object> monthMap = (Map<String, Object>) res.get(mark.get(key));
				List<Object> monthRepays = (ArrayList<Object>) monthMap.get("monthRepays");
				Map<String,Object> dayMap;
				if(mark.containsKey(dayKey)) {
					dayMap = (Map<String,Object>) monthRepays.get(mark.get(dayKey));
					List<Repay> dayRepays = (List<Repay>) dayMap.get("dayRepays");
					dayRepays.add(r);
					dayMap.put("total", Money.format((double) dayMap.get("total") + r.getPeriodTotal()));
					dayMap.put("dayRepays", dayRepays);
					monthRepays.set(mark.get(dayKey), dayMap);
				} else {
					dayMap = new HashMap<String,Object>();
					List<Repay> dayRepays = new ArrayList<Repay>();
					dayRepays.add(r);
					dayMap.put("name", DateUtil.format(r.getRepayTime(), "dd"));
					dayMap.put("total", r.getPeriodTotal());
					dayMap.put("dayRepays", dayRepays);
					monthRepays.add(dayMap);
					mark.put(dayKey, monthRepays.size()-1);
				}
				monthMap.put("total", Money.format((double) monthMap.get("total") + r.getPeriodTotal()));
				monthMap.put("monthRepays", monthRepays);
				res.set(mark.get(key), monthMap);
			} else {
				Map<String,Object> monthMap = new HashMap<String,Object>();
				List<Object> monthRepays = new ArrayList<Object>();
				Map<String,Object>  dayMap = new HashMap<String,Object>();
				List<Repay> dayRepays = new ArrayList<Repay>();
				dayRepays.add(r);
				dayMap.put("name", DateUtil.format(r.getRepayTime(), "dd"));
				dayMap.put("total", r.getPeriodTotal());
				dayMap.put("dayRepays", dayRepays);
				monthRepays.add(dayMap);
				monthMap.put("name", key);
				monthMap.put("total", r.getPeriodTotal());
				monthMap.put("monthRepays", monthRepays);
				res.add(monthMap);
				mark.put(key, res.size()-1);
				mark.put(dayKey, monthRepays.size()-1);
			}
		}
		renderJson(Json.ok("数据获取成功！", Data.put("repays", res, "count", list.size(), "total",String.valueOf(Money.format(total)))));
	}
	
	/**
	 * 还款项目列表 
	 */
	public void list() { 
		int page = getParaToInt("page",1);
		int size = getParaToInt("size",10);
		Map<String,String> params = Data.flat(getParaMap());
		Page<Repay> p = repay.list(page,size,params);

		double total = 0.0;
		double total_amount = 0.0;
		double total_interest = 0.0;
		double total_plus = 0.0;
		double total_jxq = 0.0;
		int count = 0;
		double pay = 0.0;
		double pay_amount = 0.0;
		double pay_interest = 0.0;
		double pay_plus = 0.0;
		double pay_jxq = 0.0;
		int pay_count = 0;
		
		for(Repay r : repay.findByParams(params)) {
			total += r.getPeriodTotal();
			total_amount += r.getAmount();
			total_interest += r.getInterest();
			total_plus += r.getPlus();
			total_jxq += r.getJxq();
			count ++;
			if(Str.eq("process", r.getStatus())) {
				pay += r.getPeriodTotal();
				pay_interest += r.getInterest();
				pay_amount += r.getAmount();
				pay_plus += r.getPlus();
				pay_jxq += r.getJxq();
				pay_count ++;
			}
		}
		renderJson(Json.ok("数据获取成功！", Data.put("page", p, "total",Money.format(total),"total_amount",Money.format(total_amount),"total_interest",Money.format(total_interest),"total_plus",Money.format(total_plus),"total_jxq",Money.format(total_jxq),
			"pay",Money.format(pay),"pay_amount",Money.format(pay_amount),"pay_interest",Money.format(pay_interest),"pay_plus",Money.format(pay_plus),"pay_jxq",Money.format(pay_jxq),"count",Money.format(count),"pay_count",Money.format(pay_count))));
	}	

	/**
	 * 还款项目列表
	 */
	@RequiresRoles("admin")
	public void bids() { 
		int page = getParaToInt("page",1);
		int size = getParaToInt("size",10);
		Map<String,String> params = Data.flat(getParaMap());
		Page<Repay> p = repay.groupByBid(page,size,params);
		p.getList().forEach(n->{
			User u = User.me.findById(n.getRepayUserId());
			n.put("fund", u!=null ? u.getRealName() : "无信息");
			n.put("bid", Bid.me.findById(n.getBidId()));
		});
		double total = 0.0;
		double total_amount = 0.0;
		double total_interest = 0.0;
		double total_plus = 0.0;
		double total_jxq = 0.0;
		int count = 0;
		double pay = 0.0;
		double pay_amount = 0.0;
		double pay_interest = 0.0;
		double pay_plus = 0.0;
		double pay_jxq = 0.0;
		int pay_count = 0;
		
		for(Repay r : repay.findByParams(params)) {
			total += r.getPeriodTotal();
			total_amount += r.getAmount();
			total_interest += r.getInterest();
			total_plus += r.getPlus();
			total_jxq += r.getJxq();
			count ++;
			if(Str.eq("process", r.getStatus())) {
				pay += r.getPeriodTotal();
				pay_interest += r.getInterest();
				pay_amount += r.getAmount();
				pay_plus += r.getPlus();
				pay_jxq += r.getJxq();
				pay_count ++;
			}
		}
		renderJson(Json.ok("数据获取成功！", Data.put("page", p, "total",Money.format(total),"total_amount",Money.format(total_amount),"total_interest",Money.format(total_interest),"total_plus",Money.format(total_plus),"total_jxq",Money.format(total_jxq),
			"pay",Money.format(pay),"pay_amount",Money.format(pay_amount),"pay_interest",Money.format(pay_interest),"pay_plus",Money.format(pay_plus),"pay_jxq",Money.format(pay_jxq),"count",Money.format(count),"pay_count",Money.format(pay_count))));
	}	
	
	/**
	 * 还款触发器
	 * @throws Exception 
	 */
	@RequiresRoles("admin")
	public void index() throws Exception {
		Bid b = Bid.me.findById(getParaToInt("bidId",0));
		if(b!=null && Str.eq(BidStatus.REPAYING, b.getStatus())){
			RepayService.run(b.getId());
			renderJson(Json.ok("还款成功！"));
		}else{
			renderJson(Json.error("标的状态不正确！"));
		}
	}
	

	@RequiresRoles("admin")
	public void handle() {
		RepayService.run(0);
		renderJson("ok");
	}
}
 